import React, { useState, useMemo, useEffect } from 'react';
import { obj_int, obj_str, ColView, filter_list, useHigh, GridTable, filter_row, useCmd, WaitUmd, MainView, BtTxt,
    uJob, cline, trim_data, KFile, loc_dt, no_del, stock_log, HandView, Title, d_sort, PanelFind, Btn, is_empty, loc } from 'sui';
import { load_col, load_supply } from 'stock/base/cmd';
import { useAccess } from 'cache';
import { DlgNum } from './ctl';
import { User } from 'cache';
import { TraceView } from './trace';
import { ignore_col, load_tech, get_ck, get_col, fix_col } from './cmd';

const SimpleView = ({ mod, submod, title, acc }) => {
    const [cur_num, curNum] = useState(0);
    const [open_num, openNum] = useState(false);
    const [map_supply, mapSupply] = useState();
    const [supply, setSupply] = useState();
    const [tech, setTech] = useState();
    const [col, setCol] = useState();
    const [high] = useHigh(140, 100);
    const [no_acc] = useAccess();
    const umd = useCmd(`file/list/${mod}`, null, null, "tech");

    useEffect(() => {
        load_tech(setTech, submod);
        load_col(mod, setCol);
        load_supply(submod, setSupply, mapSupply);
    }, [mod, submod]);

    useEffect(() => {
        const data = umd.value;
        if (is_empty(data)) {
            curNum(0);
            return;
        }

        let tmp = 0;
        data.forEach(d => tmp += obj_int(d, "dnum"));
        curNum(tmp);
    }, [umd.value]);

    const getRow = useMemo(() => {
        let data = umd.value;
        if (!data) {
            return null;
        }

        const lst = filter_list(["sn"], col);
        const ret = filter_row(data, lst, umd.filter);

        d_sort(ret, "tech");

        return ret;
    }, [umd.value, umd.filter, col]);

    const pact = {
        "del": (v) => {
            if (no_del()) {
                return;
            }

            const sn = obj_str(v, "sn");

            umd.update(`file/rm/${mod}`, { sn: sn });

            stock_log(`lg${mod}`, sn, "del", v);
        },
        "num": () => openNum(true),
        "check": () => openNum(true),
    };

    const act = {
        "add": (v, h) => {
            const tech_sn = obj_str(v, "tech");
            const sn = `${tech_sn}-${obj_str(v, "supply")}`;

            const val = {
                ...v,
                sn: sn,
                uname: User.uName(),
                end: loc_dt(new Date()),
            };

            if (submod === "lathe") {
                const f = tech.find(d => d.sn === tech_sn);
                if (!f) {
                    alert(loc("l_761"));
                    return;
                }

                val["ball"] = obj_str(f, "ball");
            }

            umd.update(`file/md/${mod}`, { sn: sn, v: val }, h);

            stock_log(`lg${mod}`, sn, "in", val);
        },
        "check": (v) => {
            const sn = obj_str(umd.cur, "sn");

            const cmd = {
                ...v,
                tp: submod,
                sn: sn,
                uname: User.uName(),
                end: loc_dt(new Date()),
                line: cline(),
            };

            umd.startWait();

            uJob(null, "out/check", cmd,
                r => umd.reload(umd.endWait),
                e => umd.setErr());
        },
        "num": (v) => {
            const sn = obj_str(umd.cur, "sn");

            const val = {
                ...v,
                uname: User.uName(),
                end: loc_dt(new Date()),
            };

            umd.update(`file/md/${mod}`, { sn: sn, v: val });

            const tmp = {
                ...umd.cur,
                num: obj_str(v, "dnum"),
            }

            stock_log(`lg${mod}`, sn, "md", tmp);
        },
    };

    const hreturn = () => {
        load_col(mod, setCol);
        umd.hreturn();
    };

    if (umd.isFin("col")) {
        const list = [
            {sn: mod, name: title, fix: fix_col()},
            {sn: `trace${mod}`, name: loc("l_112") },
        ];

        return <ColView hreturn={hreturn} title={title} subtitle={loc("l_221")} list={list} cur={mod}/>;
    }

    if (umd.isFin("trace")) {
        return <TraceView hreturn={umd.hreturn} title={title} mod={mod}/>;
    }

    const hCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const ret = [];
        const set = ignore_col();

        col.forEach(d => {
            if (set.has(d.sn)) {
                return;
            }

            if (d.sn === "supply") {
                d.ctp = "list";
                d.ctl = supply;
            } else if (d.sn === "sn") {
                d.ctp = "auto";
            } else if (d.sn === "tech") {
                if (submod !== "blank") {
                    d.ctp = "list";
                    d.ctl = tech;
                }
            }

            ret.push(d);
        });

        return ret;
    };

    if (umd.isFin("add")) {
        return <HandView umd={umd} title={title} act={act} col={hCol()} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 200, frozen: true, formatter: props => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(pact, d, "del")} disabled={no_acc(acc)}>{loc("l_237")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "num")} disabled={no_acc(acc)}>{loc("l_740")}</BtTxt>
                        <BtTxt hcmd={() => umd.pact(pact, d, "check")} disabled={no_acc(acc)}>{loc("l_154")}</BtTxt>
                    </div>
                );
            }},
        ];

        get_col(col, tmp, map_supply);

        return tmp;
    };

    const getList = () => {
        if (is_empty(col)) {
            return null;
        }

        return col.map(d => d.sn);
    };

    const rowTempl = () => {
        const tmp = getList();
        if (is_empty(tmp)) {
            return null;
        }

        const v = {};
        tmp.forEach(k => v[k] = "1");

        return [v];
    };

    const hImport = (val) => {
        if (is_empty(col)) {
            alert(loc("l_686"));
            return;
        }

        if (is_empty(val)) {
            alert(loc("l_276"));
            return;
        }

        trim_data(val, ["sn"]);

        const cmd = {};

        val.forEach(d => {
            cmd[d.sn] = d;
        })

        umd.update(`file/modify/${mod}`, {v: cmd});
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn color="teal" hcmd={() => umd.pact(null, null, "trace")}>{loc("l_112")}</Btn>
            <Btn color="green" hcmd={() => umd.pact(null, null, "add")} className="mx-4" disabled={no_acc(acc)}>{loc("l_239")}</Btn>
            <KFile umd={umd} title={title} col={getList()} row={rowTempl()} hcmd={hImport} no_acc_in={no_acc(acc + "a")}/>
            <Btn className="mx-4" hcmd={() => umd.pact(null, null, "col")} disabled={no_acc(acc)}>{loc("l_221")}</Btn>
        </div>
    );

    const Left = () => (
        <div className="inline-flex items-center">
            <Title mod={title} sub={loc("l_138")}/>
            <div className="ml-10 bg-teal-300 px-3 pt-2 pb-1">{loc("l_127")}<span className="ml-6">{cur_num}</span></div>
        </div>
    );

    return (
        <MainView>
            <PanelFind left={<Left/>} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable col={getCol()} row={getRow} high={high}/>
            <DlgNum open={open_num} setOpen={openNum} hcmd={v => umd.act(act, v)} data={umd.cur} col={col} fin={umd.fin}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {SimpleView};
